package indi.kider.server.applet.service;

import com.alibaba.fastjson.JSON;
import indi.kider.common.constant.LeaseBusStateCons;
import indi.kider.common.constant.RentStateCons;
import indi.kider.common.model.apabus.LeaseBus;
import indi.kider.common.model.apabus.LeaseBusVo;
import indi.kider.common.model.apabus.LeaseModel;
import indi.kider.common.model.apabus.Rent;
import indi.kider.common.model.apartment.Houses;
import indi.kider.server.apabus.mapper.LeaseBusMapper;
import indi.kider.server.apabus.mapper.RentMapper;
import indi.kider.server.apartment.mapper.HousesMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 退租、换房申请接口实现
 *
 * @author wangjingjing
 * @create 2018-10-22 上午11:24
 **/
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
@Slf4j
public class LeaseBusServiceImpl implements LeaseBusService {

    @Autowired
    private LeaseBusMapper leaseBusMapper;

    @Autowired
    private RentMapper rentMapper;

    @Autowired
    private HousesMapper housesMapper;

    @Override
    public boolean applyfor(LeaseModel leaseModel, Integer leaseType) throws Exception {
        Rent rent = new Rent();
        rent.setTenantId(leaseModel.getTenantId());
        rent.setState(RentStateCons.VALID);
        Rent rent1 = rentMapper.selectOne(rent);
        if (rent1 == null) {
            throw new Exception("用户没有查询到入住信息");
        }
        //换房判断性别和房间的住在人员情况
        if (leaseType == 2) {
            checkSexInHouse(rent1.getCardId(), leaseModel.getNewRoomId());
        }
        leaseModel.setRentId(rent1.getId());
        log.info("【申请业务{}】", JSON.toJSONString(leaseModel));


        LeaseBus leaseBus = trucLeaseModel(leaseModel, leaseType);
        if (!checkSomeInfoToBus(leaseBus)) {
            throw new Exception("不可以重复提交申请");
        }
        int x = leaseBusMapper.insertSelective(leaseBus);
        log.info("【申请业务{}, 结果{}】", JSON.toJSONString(leaseModel), x);
        return true;
    }

    @Override
    public LeaseBus queryStateByTenantId(Long rentId) {

        /*存在风险是如果退房和换房同时存在。*/
        Example example = new Example(LeaseBus.class);
        example.createCriteria().
                andEqualTo("rentId", rentId).
                andLessThan("busState", LeaseBusStateCons.HOMEKEEPER_REVIEW);

        List<LeaseBus> leasebus = leaseBusMapper.selectByExample(example);
        if (leasebus == null || leasebus.size() < 1) {
            return null;
        } else {
            return leasebus.get(0);
        }

    }

    @Override
    public LeaseBus trucLeaseModel(LeaseModel leaseModel, Integer leaseType) {
        LeaseBus leaseBus = new LeaseBus();
        leaseBus.setBusType(leaseType);
        leaseBus.setRentId(leaseModel.getRentId());
        leaseBus.setResone(leaseModel.getReason());
        leaseBus.setHouseId(leaseModel.getNewRoomId());
        leaseBus.setBusState(0);
        leaseBus.setTime(new Date());
        return leaseBus;
    }

    @Override
    public LeaseBusVo trucLeaseBus(LeaseBus leaseBus) {
        LeaseBusVo leaseBusVo = new LeaseBusVo();
        Integer    state      = -1;
        if (!(leaseBus == null)) {
            state = leaseBus.getBusState();
        }
        leaseBusVo.setLeaseCode(state);
        leaseBusVo.setInfo(LeaseBusStateCons.MAP.get(state));
        leaseBusVo.setType(leaseBus.getBusType());
        return leaseBusVo;
    }

    boolean checkSexInHouse(String carId, Long houseId) throws Exception {
        Houses houses = housesMapper.selectByPrimaryKey(houseId);
        String sex    = getSexByNumbs(carId);
        if (houses.getMaxCnt() == houses.getInSumCnt()) {
            throw new Exception("此房间已经满员！");
        }
        // 男
        if ("1".equals(sex) && houses.getInFemanCnt() > 0) {
            throw new Exception("此房间是女生专住！");
        }
        if ("2".equals(sex) && houses.getInManCnt() > 0) {
            throw new Exception("此房间是男生专住！");
        }

        return true;
    }

    /**
     * 校验是否重复提交
     *
     * @param leaseBus
     * @return
     */
    boolean checkSomeInfoToBus(LeaseBus leaseBus) {
        Example example = new Example(LeaseBus.class);
        example.createCriteria().andLessThan("busState", 3)
                .andEqualTo("rentId", leaseBus.getRentId());
        List<LeaseBus> list = leaseBusMapper.selectByExample(example);
        return (list == null || list.isEmpty());
    }

    /**
     * 2表示女
     * 1表示男
     *
     * @param idNum
     * @return
     */
    public static String getSexByNumbs(String idNum) {
        idNum = idNum.trim();
        String sex = "";
        if (idNum.matches("^\\d{15}$|^\\d{17}[\\dxX]$")) {
            if (idNum.length() == 18) {
                Pattern pattern = Pattern.compile("\\d{6}(\\d{4})\\d{6}(\\d{1})[\\dxX]{1}");
                Matcher matcher = pattern.matcher(idNum);
                if (matcher.matches()) {
                    sex = "" + Integer.parseInt(matcher.group(2)) % 2;
                }
            } else if (idNum.length() == 15) {
                Pattern p = Pattern.compile("\\d{6}(\\d{2})\\d{5}(\\d{1})\\d{1}");
                Matcher m = p.matcher(idNum);
                if (m.matches()) {
                    sex = "" + Integer.parseInt(m.group(2)) % 2;
                }
            }
        }
        if ("0".equals(sex)) {
            sex = "2";
        }
        return sex;
    }
}
